package com.iwhalecloud.bss.kite.cucc.web.controller.collection;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.batch.IBatchAcceptService;
import com.iwhalecloud.bss.kite.cucc.client.api.collection.ICollectionGroupImportService;
import com.iwhalecloud.bss.kite.cucc.client.dto.customerOrderInformation.CustOrderInfoRegion;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.batch.BatchAcceptUtil;
import com.iwhalecloud.bss.kite.cucc.service.util.ExcelUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.base.annotation.IgnoreSession;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lyx
 * @version V1.0
 * @Description: TODO
 * @date 2021年2月20日
 * @Package com.iwhalecloud.bss.kite.cucc.web.controller.order
 */
@RestController
@RequestMapping("/collectionGroup")
@Api(tags = {"/collectionGroup - 收入归集集团"})
public class CollectionGroupController {

    @Autowired
    private ICollectionGroupImportService collectionGroupImportService;

    @Resource
    private IBatchAcceptService batchAcceptService;

    @ApiOperation(value = "归集集团创建导入", notes = "归集集团创建导入")
    @PostMapping(produces = "application/json;charset=utf-8", value = "/createCollectionGroupImport")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "file", paramType = "form")
    })
    public DataResult<String> createCollectionGroupImport(
        @RequestParam(value = "file", required = true) MultipartFile file, String sceneInstId) throws IOException {

        String fileName = file.getOriginalFilename();
        String fileType = KiteStringUtils.substring(fileName, fileName.lastIndexOf('.') + 1);
        if (!KiteStringUtils.equalsAny(fileType, "xls", "xlsx")) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("只允许上传excel格式文件");
        }
        boolean isXls = "xls".equals(fileName.substring(fileName.lastIndexOf('.') + 1));
//        String result = collectionGroupImportService.createCollectionGroupImport(file.getInputStream(), isXls, sceneInstId, fileName);
        String result = batchAcceptService.importData(file.getInputStream(), isXls, sceneInstId, fileName, LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_1000);

        return ErrorConsts.SUCCESS.getResult(result);
    }

    @ApiOperation(value = "归集集团成员加入导入、成员退出导入", notes = "归集集团成员加入导入、成员退出导入")
    @PostMapping(produces = "application/json;charset=utf-8", value = "/collectionGroupImport")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "file", paramType = "form"),
        @ApiImplicitParam(name = "sceneInstId", value = "订单标识", required = true),
        @ApiImplicitParam(name = "importType", value = "订单标识", required = false)
    })
    public DataResult<String> colectionGroupImport(
        @RequestParam(value = "file") MultipartFile file, @RequestParam String sceneInstId, @RequestParam(required = false) String importType) throws IOException {

        String fileName = file.getOriginalFilename();
        String fileType = KiteStringUtils.substring(fileName, fileName.lastIndexOf('.') + 1);
        if (!KiteStringUtils.equalsAny(fileType, "xls", "xlsx")) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("只允许上传excel格式文件");
        }
        boolean isXls = "xls".equals(fileName.substring(fileName.lastIndexOf('.') + 1));

//        String result = collectionGroupImportService.collectionGroupImport(file.getInputStream(), isXls, sceneInstId, fileName, importType);
        String resultMsg = "";
        try {
            resultMsg = batchAcceptService.importData(file.getInputStream(), isXls, sceneInstId, fileName, importType);
            return ErrorConsts.SUCCESS.getResult(resultMsg);
        }
        catch (BssException e) {
            resultMsg = e.getMessage();
        }
        DataResult<String> result = ErrorConsts.BUSI_CHECK_ERROR.getResult(resultMsg);
        result.setResultMsg(result.getResultObject());
        return result;
    }

    @ApiOperation(value = "归集集团成员加入导入、成员退出保存", notes = "归集集团成员加入导入、成员退出保存")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id")
    })
    @GetMapping("/saveColectionGroupImport")
    public DataResult<String> saveColectionGroupImport(String sceneInstId, String custId) {
//        String result = collectionGroupImportService.saveColectionGroupImport(sceneInstId, custId);
        String result = batchAcceptService.saveImport(sceneInstId, custId);

        return ErrorConsts.SUCCESS.getResult(result);
    }

    @KiteTransactional
    @ApiOperation(value = "归集集团成员加入、成员退出场景保存", notes = "归集集团成员加入、成员退出场景保存")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id")
    })
    @PostMapping("/saveColectionGroupMenberUserInfo")
    public DataResult<String> saveColectionGroupMenberUserInfo(@RequestParam String sceneInstId, @RequestBody List<Map<String, Object>> data) {
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        String provinceId = loginInfo.getUserInfo().getPostProvinceNbr();
        String lanId = loginInfo.getUserInfo().getPostLanId();
        String regionId = loginInfo.getUserInfo().getPostRegionId().toString();
        String staffId = loginInfo.getUserInfo().getUserId().toString();
        String result = collectionGroupImportService.saveColectionGroupMenberUserInfo(sceneInstId, KiteWebContext.getContext().getCustId(), provinceId, lanId, regionId, staffId, data);

        return ErrorConsts.SUCCESS.getResult(result);
    }

    @ApiOperation(value = "查询导入日志批次", notes = "查询导入日志批次")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "query", value = "查询条件"),
    })
    @PostMapping("/queryKiteGroupBatchLog")
    public DataResult<PageInfo<Map<String ,Object>>> queryKiteGroupBatchLog(@RequestBody Map<String, Object> query) {
        return ErrorConsts.SUCCESS.getResult(collectionGroupImportService.queryKiteGroupBatchLog(query));
    }

    @ApiOperation(value = "查询导入日志明细", notes = "查询导入日志明细")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "query", value = "查询条件"),
    })
    @PostMapping("/queryKiteGroupDetailLog")
    public DataResult<PageInfo<Map<String, Object>>> queryKiteGroupDetailLog(@RequestBody Map<String, Object> query) {
        return ErrorConsts.SUCCESS.getResult(collectionGroupImportService.queryKiteGroupDetailLog(query));
    }

    @IgnoreSession
    @ApiOperation(value = "导出日志明细", notes = "导出日志明细")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "batchId", value = "批次号"),
    })
    @GetMapping("/exportDetailLog")
    public void exportDetailLog(String batchId, String importType, HttpServletRequest request, HttpServletResponse response) {
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            String fileName = "校验结果.xls";// 文件名
            Map<String, Object> fileTitleMap = new HashMap<>();// 文件名
            LinkedHashMap<String, String> sheetTitleMap = new LinkedHashMap<>();// 表格
            List<Map<String, Object>> dataList = collectionGroupImportService.queryKiteGroupBatchLogForList(batchId);
            dataList.stream().forEach(data -> {
                String attrJson = KiteMapUtils.getString(data, "attr_json");
                if (KiteStringUtils.isNotEmpty(attrJson)) {
                    if (KiteStringUtils.equalsAny(importType, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_4000, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_5000)) {
                        List<Map> attrs = JSONArray.parseArray(attrJson, Map.class);
                        attrs.forEach(attr -> {
                            data.put(KiteMapUtils.getStrValue(attr, "fieldName"), attr.get("value"));
                            sheetTitleMap.put(KiteMapUtils.getStrValue(attr, "fieldName"), KiteMapUtils.getStrValue(attr, "cname"));
                        });
                    }
                    else if (KiteStringUtils.equalsAny(importType, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_7100, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_7200)) {
                        Map<String, String> nodeMap = BatchAcceptUtil.delBatchNodeLog(attrJson);
                        data.putAll(nodeMap);
                        nodeMap.forEach((k, v) -> sheetTitleMap.put(k, k));
                    }
                    else {
                        List<Map> attrs = JSONArray.parseArray(attrJson, Map.class);
                        attrs.forEach(attr -> {
                            data.put(KiteStringUtils.camelToUnderline(KiteMapUtils.getStrValue(attr, "fieldName")),
                                attr.get("value"));
                            // sheetTitleMap.put(KiteMapUtils.getStrValue(attr, "fieldName"), KiteMapUtils.getStrValue(attr, "cname"));
                        });
                    }
                }
                String checkStatusValue = KiteMapUtils.getStrValue(data, "check_status");
                if (KiteStringUtils.equals(checkStatusValue, LocalKeyConsts.COLLECTION_GROUP_CHECK_STATUS_1000)) {
                    data.put("check_status", "未校验");
                }
                if (KiteStringUtils.equals(checkStatusValue, LocalKeyConsts.COLLECTION_GROUP_CHECK_STATUS_1100)) {
                    data.put("check_status", "校验失败");
                }
                if (KiteStringUtils.equals(checkStatusValue, LocalKeyConsts.COLLECTION_GROUP_CHECK_STATUS_1200)) {
                    data.put("check_status", "校验成功");
                }

                String dealDescValue = KiteMapUtils.getStrValue(data, "deal_result");
                if (KiteStringUtils.isEmpty(dealDescValue)) {
                    data.put("deal_desc", "无处理结果");
                }
                else {
                    data.put("deal_desc", dealDescValue);
                }
                String telecomTypeValue = KiteMapUtils.getStrValue(data, "telecom_type");
                if (!KiteStringUtils.isEmpty(telecomTypeValue)) {
                    AttrValue attrValue = AttrValueCache.getAttrValue("20210304001", telecomTypeValue);
                    data.put("telecom_type", attrValue.getAttrValueName());
                }
            });
            if (KiteStringUtils.equals(importType, LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_1000)){
                fileTitleMap.put("title", "收入归集集团创建校验结果");
                fileName = "收入归集集团创建校验结果.xls";
            }
            if(KiteStringUtils.equals(importType, LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_2000)){
                fileTitleMap.put("title", "归集集团成员加入校验结果");
                fileName = "归集集团成员加入校验结果.xls";
            }
            if(KiteStringUtils.equals(importType, LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_3000)){
                fileTitleMap.put("title", "归集集团成员退出校验结果");
                fileName = "归集集团成员退出校验结果.xls";
            }
            if(KiteStringUtils.equals(importType, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_4000)){
                fileTitleMap.put("title", "批量业务受理提交结果");
                fileName = "批量业务受理提交结果.xls";
            }
            if(KiteStringUtils.equals(importType, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_5000)){
                fileTitleMap.put("title", "批量资源核查提交结果");
                fileName = "批量业务受理提交结果.xls";
            }
            if (KiteStringUtils.equals(importType, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_7100)){
                fileTitleMap.put("title", "批量签订提交结果");
                fileName = "批量签订提交结果.xls";
            }
            if (KiteStringUtils.equals(importType, LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_7200)){
                fileTitleMap.put("title", "批量起租提交结果");
                fileName = "批量起租提交结果.xls";
            }
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            List<DcPublic> dcPublics = DcPublicCache.get("2021420001");
            if(KiteListUtils.isNotEmpty(dcPublics)){
                dcPublics = dcPublics.stream().filter(dcPublic -> KiteStringUtils.equals(importType,dcPublic.getPkey())).collect(Collectors.toList());
                dcPublics.stream().forEach(dcPublic ->{
                    sheetTitleMap.put(dcPublic.getPcode(),dcPublic.getPname());
                });
                //固化校验结果列和订单提交结果列
                sheetTitleMap.put("check_status", "校验结果");
                sheetTitleMap.put("deal_desc", "订单提交结果");
            }
            ExcelUtil.exportExcelDocument(fileTitleMap, sheetTitleMap, dataList, out);
        }
        catch (Exception e) {
//            e.printStackTrace();
        }
        finally {
            try {
                if (null != out) {
                    out.close();
                }
            }
            catch (IOException e) {
//                e.printStackTrace();
            }
        }
    }

    @ApiOperation(value = "获取查询条件中归属地省份", notes = "获取批量导入结果中查询条件中归属地省份")
    @GetMapping("/province")
    public DataResult<CustOrderInfoRegion> getProvince() {
        return ErrorConsts.SUCCESS.getResult(collectionGroupImportService.getProvince());
    }

    @ApiOperation(value = "获取查询条件中归属地地市", notes = "获取批量导入结果中查询条件中归属地地市")
    @ApiImplicitParams({@ApiImplicitParam(name = "provinceCode", value = "省份编码", required = true)})
    @GetMapping("/city")
    public DataResult<CustOrderInfoRegion> getCity(@RequestParam String provinceCode) {
        return ErrorConsts.SUCCESS.getResult(collectionGroupImportService.getCity(provinceCode));
    }
}
